package com.kczd.jinlan.view.mine;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;

import com.bigkoo.pickerview.OptionsPickerView;
import com.bigkoo.pickerview.listener.CustomListener;
import com.kczd.jinlan.R;
import com.kczd.jinlan.model.Adress;
import com.kczd.jinlan.model.City;
import com.kczd.jinlan.model.Province;
import com.kczd.jinlan.model.Street;
import com.kczd.jinlan.utils.Config;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;

import cn.pedant.SweetAlert.SweetAlertDialog;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * yang_g
 * 新增地址
 * Created by Administrator on 2017/5/23.
 */

public class AddLocationActivity extends Activity implements View.OnClickListener, CompoundButton.OnCheckedChangeListener {
    public final static String TAG = "AddLocationActivity.class";
    private TextView text_choice_p;//省份选择器
    private TextView text_choice_c;//城市选择器
    private TextView text_choice_x;//县区选择器
    private EditText edit_choice_s;//街道选择器
    private TextView id_fanhui;//返回
    private OptionsPickerView choice_p, choice_c, choice_x, choice_s;
    private ArrayList<Province> cardItem = new ArrayList<>();
    private ArrayList<City> cardItemcity = new ArrayList<>();
    private ArrayList<Adress> cardItemadress = new ArrayList<>();
    private ArrayList<Street> cardItemstreet = new ArrayList<>();

    private EditText username;
    private EditText moblie;
    private Button submit_save;
    private ToggleButton toggleButton = null;
    private String msgdef;//设置默认地址

    private String address_id;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.addlocation_activity);


        new Thread(new Runnable() {
            @Override
            public void run() {
                initData();//初始化省份
            }
        }).start();


    }

    @Override
    public void onContentChanged() {
        super.onContentChanged();
        Intent intent = getIntent();
        address_id = intent.getStringExtra("address_id");
        Log.e("address_id", address_id);
        text_choice_p = (TextView) findViewById(R.id.text_choice_p);
        text_choice_p.setOnClickListener(this);
        text_choice_c = (TextView) findViewById(R.id.text_choice_c);
        text_choice_c.setOnClickListener(this);
        text_choice_x = (TextView) findViewById(R.id.text_choice_x);
        text_choice_x.setOnClickListener(this);
        id_fanhui = (TextView) findViewById(R.id.id_fanhui);
        id_fanhui.setOnClickListener(this);
        edit_choice_s = (EditText) findViewById(R.id.ed_choce_street);
        edit_choice_s.setOnClickListener(this);
        username = (EditText) findViewById(R.id.ed_username);
        moblie = (EditText) findViewById(R.id.ed_phone);
        submit_save = (Button) findViewById(R.id.address_save);
        submit_save.setOnClickListener(this);
        toggleButton = (ToggleButton) findViewById(R.id.tog_but);
        toggleButton.setOnCheckedChangeListener(this);

    }

    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        if (isChecked) {
            getDefault();
            Toast.makeText(AddLocationActivity.this, msgdef, Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(AddLocationActivity.this, "不默认", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.text_choice_p:
                if (choice_p != null) {
                    choice_p.show();
                }
                break;
            case R.id.address_save://保存
                if (!subpre()) {
                    new SweetAlertDialog(this, SweetAlertDialog.ERROR_TYPE)
                            .setTitleText("必填验证")
                            .setContentText("你是不是忘了填什么")
                            .show();
                    return;
                } else {
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            commitSave();
                        }
                    }).start();
                }
                break;
        }
    }

    String commiturl = Config.net_addr + "user/add_address";

    public void commitSave() {
        //创建okHttpClient对象
        OkHttpClient client = new OkHttpClient();
        RequestBody requestBody = new FormBody.Builder()
                .add("token", Config.user.getToken())
                .add("province", pid)
                .add("city", cid)
                .add("district", xid)
                .add("town", sid)
                .add("address", edit_choice_s.getText().toString())
                .add("mobile", moblie.getText().toString())
                .add("consignee", username.getText().toString())
                .build();
        Request request = new Request.Builder()
                .url(commiturl)
                .post(requestBody)
                .build();
        try {
            Response response = client.newCall(request).execute();
            String strResult = response.body().string();
            Message msg = new Message();
            Bundle data = new Bundle();
            data.putString("ret_json", strResult);
            msg.setData(data);
            commithandler.sendMessage(msg);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    Handler commithandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            Bundle data = msg.getData();
            String val = data.getString("ret_json");
            Log.e(TAG, val);
            val = val.substring(val.indexOf("{"), val.lastIndexOf("}") + 1);
            JSONObject jsonResult;
            try {
                jsonResult = new JSONObject(val);
                // UI界面的更新等相关操作
                if (Config.code.equals(jsonResult.getString("code"))) {
                    AddLocationActivity.this.finish();
                    Toast.makeText(AddLocationActivity.this, "保存成功", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(AddLocationActivity.this, jsonResult.getString("msg"), Toast.LENGTH_SHORT).show();
                }
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    };

    /**
     * 检测用户名和密码是否为空
     *
     * @return
     */
    public boolean subpre() {
        String name = username.getText().toString();
        String phone = moblie.getText().toString();
        String province = text_choice_p.getText().toString();

        if (name.isEmpty() || phone.isEmpty() || province.isEmpty()) {
            return false;
        }
        return true;
    }



    /*--------------------------------------------------------------------------------------------------------------------------------------------*/

    /**
     * 获取街道
     */
    private void initDataStreet(String id) {
        //创建okHttpClient对象
        OkHttpClient client = new OkHttpClient();
        RequestBody requestBody = new FormBody.Builder()
                .add("id", id)
                .build();
        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();
        try {
            Response response = client.newCall(request).execute();
            String strResult = response.body().string();
            Message msg = new Message();
            Bundle data = new Bundle();
            data.putString("ret_json", strResult);
            msg.setData(data);
            streethandler.sendMessage(msg);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    Handler streethandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            Bundle data = msg.getData();
            String val = data.getString("ret_json");
            Log.e(TAG, val);
            val = val.substring(val.indexOf("{"), val.lastIndexOf("}") + 1);
            JSONObject jsonResult;
            try {
                jsonResult = new JSONObject(val);
                // UI界面的更新等相关操作
                if (Config.code.equals(jsonResult.getString("code"))) {
                    JSONArray jb = jsonResult.getJSONArray("data");
                    for (int i = 0; i < jb.length(); i++) {
                        Street street = new Street();
                        street.setId(jb.getJSONObject(i).getString("id"));
                        street.setmName(jb.getJSONObject(i).getString("name"));
                        street.setLevel(jb.getJSONObject(i).getString("level"));
                        street.setParent_id(jb.getJSONObject(i).getString("parent_id"));
                        cardItemstreet.add(street);
                    }
                    initCustomOptionPickerStreet();
                    if (choice_s != null) {
                        choice_s.show();
                    }
                }
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    };

    /**
     * 获取县区
     */
    private void initDataAdress(String cid) {
        //创建okHttpClient对象
        OkHttpClient client = new OkHttpClient();
        Log.e("zhangy", cid);
        RequestBody requestBody = new FormBody.Builder()
                .add("id", cid)
                .build();
        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();
        try {
            Response response = client.newCall(request).execute();
            String strResult = response.body().string();
            Message msg = new Message();
            Bundle data = new Bundle();
            data.putString("ret_json", strResult);
            msg.setData(data);
            adresshandler.sendMessage(msg);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    Handler adresshandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            Bundle data = msg.getData();
            String val = data.getString("ret_json");
            Log.e(TAG, val);
            val = val.substring(val.indexOf("{"), val.lastIndexOf("}") + 1);
            JSONObject jsonResult;
            try {
                jsonResult = new JSONObject(val);
                // UI界面的更新等相关操作
                if (Config.code.equals(jsonResult.getString("code"))) {
                    JSONArray jb = jsonResult.getJSONArray("data");
                    for (int i = 0; i < jb.length(); i++) {
                        Adress city = new Adress();
                        city.setId(jb.getJSONObject(i).getString("id"));
                        city.setmName(jb.getJSONObject(i).getString("name"));
                        city.setLevel(jb.getJSONObject(i).getString("level"));
                        city.setParent_id(jb.getJSONObject(i).getString("parent_id"));
                        cardItemadress.add(city);
                    }
                    initCustomOptionPickerAdress();
                    if (choice_x != null) {
                        choice_x.show();
                    }
                }
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    };

    /**
     * 获取城市
     */
    private void initDataCity(String pid) {
        //创建okHttpClient对象
        OkHttpClient client = new OkHttpClient();
        Log.e("zhangy", pid);
        RequestBody requestBody = new FormBody.Builder()
                .add("id", pid)
                .build();
        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();
        try {
            Response response = client.newCall(request).execute();
            String strResult = response.body().string();
            Message msg = new Message();
            Bundle data = new Bundle();
            data.putString("ret_json", strResult);
            msg.setData(data);
            cityhandler.sendMessage(msg);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    Handler cityhandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            Bundle data = msg.getData();
            String val = data.getString("ret_json");
            Log.e(TAG, val);
            val = val.substring(val.indexOf("{"), val.lastIndexOf("}") + 1);
            JSONObject jsonResult;
            try {
                jsonResult = new JSONObject(val);
                // UI界面的更新等相关操作
                if (Config.code.equals(jsonResult.getString("code"))) {
                    JSONArray jb = jsonResult.getJSONArray("data");
                    for (int i = 0; i < jb.length(); i++) {
                        City city = new City();
                        city.setId(jb.getJSONObject(i).getString("id"));
                        city.setmName(jb.getJSONObject(i).getString("name"));
                        city.setLevel(jb.getJSONObject(i).getString("level"));
                        city.setParent_id(jb.getJSONObject(i).getString("parent_id"));
                        cardItemcity.add(city);
                    }
                    initCustomOptionPickerCity();
                    if (choice_c != null) {
                        choice_c.show();
                    }
                }
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    };

    /**
     * 获取省份城市
     */
    String url = Config.net_addr + "index/region_list";

    private void initData() {
        //创建okHttpClient对象
        OkHttpClient client = new OkHttpClient();
        RequestBody requestBody = new FormBody.Builder()
                .build();
        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();
        try {
            Response response = client.newCall(request).execute();
            String strResult = response.body().string();
            Message msg = new Message();
            Bundle data = new Bundle();
            data.putString("ret_json", strResult);
            msg.setData(data);
            handler.sendMessage(msg);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            Bundle data = msg.getData();
            String val = data.getString("ret_json");
            Log.e(TAG, val);
            val = val.substring(val.indexOf("{"), val.lastIndexOf("}") + 1);
            JSONObject jsonResult;
            try {
                jsonResult = new JSONObject(val);
                // UI界面的更新等相关操作
                if (Config.code.equals(jsonResult.getString("code"))) {
                    JSONArray jb = jsonResult.getJSONArray("data");
                    for (int i = 0; i < jb.length(); i++) {
                        Province province = new Province();
                        province.setId(jb.getJSONObject(i).getString("id"));
                        province.setmName(jb.getJSONObject(i).getString("name"));
                        province.setLevel(jb.getJSONObject(i).getString("level"));
                        province.setParent_id(jb.getJSONObject(i).getString("parent_id"));
                        cardItem.add(province);
                    }
                    initCustomOptionPicker();
                }
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    };
    /**
     * 初始化省份
     */
    String pid = "";

    private void initCustomOptionPicker() {//条件选择器初始化，自定义布局

        // 注意：自定义布局中，id为 optionspicker 或者 timepicker 的布局以及其子控件必须要有，否则会报空指针
        // 具体可参考demo 里面的两个自定义布局
        choice_p = new OptionsPickerView.Builder(this, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int option2, int options3, View v) {
                //返回的分别是三个级别的选中位置
                String tx = cardItem.get(options1).getPickerViewText();
                pid = cardItem.get(options1).getPickerViewId();
                text_choice_p.setText(tx);
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        initDataCity(pid);//初始化城市
                    }
                }).start();
            }
        })
                .setLayoutRes(R.layout.pickerview_custom_options, new CustomListener() {
                    @Override
                    public void customLayout(View v) {
                        final TextView tvSubmit = (TextView) v.findViewById(R.id.tv_finish);
                        ImageView ivCancel = (ImageView) v.findViewById(R.id.iv_cancel);
                        tvSubmit.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                choice_p.returnData();
                            }
                        });
                        ivCancel.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                choice_p.dismiss();
                            }
                        });

                    }
                })
                .isDialog(true)
                .build();
        choice_p.setPicker(cardItem);//添加数据
    }

    /**
     * 初始化城市
     */
    String cid = "";

    private void initCustomOptionPickerCity() {//条件选择器初始化，自定义布局

        // 注意：自定义布局中，id为 optionspicker 或者 timepicker 的布局以及其子控件必须要有，否则会报空指针
        // 具体可参考demo 里面的两个自定义布局
        choice_c = new OptionsPickerView.Builder(this, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int option2, int options3, View v) {
                //返回的分别是三个级别的选中位置
                String tx = cardItemcity.get(options1).getPickerViewText();
                cid = cardItemcity.get(options1).getPickerViewId();
                text_choice_c.setText(tx);
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        initDataAdress(cid);//初始化县区
                    }
                }).start();
            }
        })
                .setLayoutRes(R.layout.pickerview_custom_options, new CustomListener() {
                    @Override
                    public void customLayout(View v) {
                        final TextView tvSubmit = (TextView) v.findViewById(R.id.tv_finish);
                        ImageView ivCancel = (ImageView) v.findViewById(R.id.iv_cancel);
                        tvSubmit.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                choice_c.returnData();
                            }
                        });
                        ivCancel.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                choice_c.dismiss();
                            }
                        });

                    }
                })
                .isDialog(true)
                .build();
        choice_c.setPicker(cardItemcity);//添加数据
    }

    /**
     * 初始化县区
     */
    String xid = "";

    private void initCustomOptionPickerAdress() {//条件选择器初始化，自定义布局

        // 注意：自定义布局中，id为 optionspicker 或者 timepicker 的布局以及其子控件必须要有，否则会报空指针
        // 具体可参考demo 里面的两个自定义布局
        choice_x = new OptionsPickerView.Builder(this, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int option2, int options3, View v) {
                //返回的分别是三个级别的选中位置
                String tx = cardItemadress.get(options1).getPickerViewText();
                xid = cardItemadress.get(options1).getPickerViewId();
                text_choice_x.setText(tx);
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        initDataStreet(xid);//初始化县区
                    }
                }).start();
            }
        })
                .setLayoutRes(R.layout.pickerview_custom_options, new CustomListener() {
                    @Override
                    public void customLayout(View v) {
                        final TextView tvSubmit = (TextView) v.findViewById(R.id.tv_finish);
                        ImageView ivCancel = (ImageView) v.findViewById(R.id.iv_cancel);
                        tvSubmit.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                choice_x.returnData();
                            }
                        });
                        ivCancel.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                choice_x.dismiss();
                            }
                        });

                    }
                })
                .isDialog(true)
                .build();
        choice_x.setPicker(cardItemadress);//添加数据
    }

    /**
     * 初始化街道
     */
    String sid = "";

    private void initCustomOptionPickerStreet() {//条件选择器初始化，自定义布局

        // 注意：自定义布局中，id为 optionspicker 或者 timepicker 的布局以及其子控件必须要有，否则会报空指针
        // 具体可参考demo 里面的两个自定义布局
        choice_s = new OptionsPickerView.Builder(this, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int option2, int options3, View v) {
                //返回的分别是三个级别的选中位置
                String tx = cardItemstreet.get(options1).getPickerViewText();
                sid = cardItemstreet.get(options1).getPickerViewId();
                edit_choice_s.setText(tx);
            }
        })
                .setLayoutRes(R.layout.pickerview_custom_options, new CustomListener() {
                    @Override
                    public void customLayout(View v) {
                        final TextView tvSubmit = (TextView) v.findViewById(R.id.tv_finish);
                        ImageView ivCancel = (ImageView) v.findViewById(R.id.iv_cancel);
                        tvSubmit.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                choice_s.returnData();
                            }
                        });
                        ivCancel.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                choice_s.dismiss();
                            }
                        });

                    }
                })
                .isDialog(true)
                .build();
        choice_s.setPicker(cardItemstreet);//添加数据
    }

    private static String DEFAUL_URL = Config.net_addr + "user/set_default";

    /*
    * 默认地址请求
    * */
    private void getDefaultHttp() {
        //创建okHttpClient对象
        OkHttpClient client = new OkHttpClient();
        RequestBody requestBody = new FormBody.Builder()
                .add("token", Config.user.getToken())
                .add("id", address_id)
                .build();

        Request request = new Request.Builder()
                .url(DEFAUL_URL)
                .post(requestBody)
                .build();
        try {
            Response response = client.newCall(request).execute();
            String strResult = response.body().string();
            Message msg = new Message();
            Bundle data = new Bundle();
            data.putString("ret_json", strResult);
            msg.setData(data);
            handlerDefault.sendMessage(msg);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    Handler handlerDefault = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            Bundle data = msg.getData();
            String val = data.getString("ret_json");
            val = val.substring(val.indexOf("{"), val.lastIndexOf("}") + 1);
            Log.e("handlerDefault", val);
            JSONObject jsonObject;
            try {
                jsonObject = new JSONObject(val);
                msgdef = jsonObject.getString("msg");

            } catch (JSONException e) {
                e.printStackTrace();
            }

        }
    };

    private void getDefault() {

        new Thread(new Runnable() {
            @Override
            public void run() {
                getDefaultHttp();
            }
        }).start();
    }

}
